<?php

class Talktangle_AdsController extends Core_Controller_Action_Standard
{
  public function indexAction()
  {
    $this->view->someVar = 'someVal';
  }
  
  public function createAction(){
	
    if( !$this->_helper->requireUser()->isValid() ) {
		return;
	}
     $this->view->viewer = $viewer = Engine_Api::_()->user()->getViewer();
     $this->view->form = $form = new Talktangle_Form_Ads_Create();

    // Check post
    if(!$this->getRequest()->isPost()){
        return;
    }
    $this->view->isValidF = true;
    // Check form validate
    if(!$form->isValid($this->getRequest()->getPost())){
        $this->view->isValidF = false;
        return;
    }

    $values = $form->getValues(); 

        
    //add value to ads
    $adsTable = Engine_Api::_()->getDbTable('ads','talktangle');
    //save form values
    $db = $promotiontable->getAdapter();
    $db->beginTransaction();
    try
    {                     
        $ads = $adsTable->createRow();
        
        $ads->owner_id = $viewer->getIdentity();
        if($values['ads_title']){
            $ads->title = $values['ads_title'];      
        }    
        if($values['ads_description']){
            $ads->description = $values['ads_description'];           
        }                  
              
        if($values['file_id']){
            $ads->photo_id = $values['file_id'];          
        }     
    
        $ads->save(); 
        $db->commit();      
    }          
    catch(Exception $e)
    {
        $db->rollBack();
        throw $e;
    }            
                      
  }
  
  public function previewAction(){
        if(!$this->getRequest()->isPost()) return;
        $table = Engine_Api::_()->getDbTable('ads','talktangle'); 
        $file_id = $table->setPhoto($_FILES['ads_image']); 
        $type = 'thumb.normal';
        $file = Engine_Api::_()->getItemTable('storage_file')->getFile($file_id, $type);
            if( !$file ) {
                return ;
            } 
        //get normal photo to save           
        $file_url = $file->map();
        $this->view->file_url = $file_url;
        $this->view->file_id = $file_id;
        
        //get full size photo to preview
        $preview = Engine_Api::_()->getItemTable('storage_file')->getFile($file_id);
        $preview_url = $preview->map();
        $this->view->preview_url = $preview_url;                
  }
  
    protected function continueProcessBuy($deal,$groupon, $form) {
    	
        // Get gateway
        $gatewayId = 2;	//Always is PayPay
        if( !$gatewayId ||
                !($gateway = Engine_Api::_()->getItem('payment_gateway', $gatewayId))
               ) {
            return $form->addError(Zend_Registry::get('Zend_Translate')->_('Paypal is disabled. Please contact to administrator for more details'));
        }
        $this->view->gateway = $gateway;
//        $this->view->groupon = $groupon;

        // Validate Paypal API
//    	if ($deal->payment_type == Groupon_Model_Deal::PAYMENT_USER_MERCHANT) {
//    		if (empty($deal->owner_id)) {
//    			return $this->_forward('notfound');
//    		}
//	    	$grouponCore = Engine_Api::_()->groupon();
//	        $account = $grouponCore->getGrouponAccount($deal->owner_id);
//	        if (empty($account)) {
//	            return $this->_forward('notfound');
//	        }
//	        
//	        if($account->paypal_api_enable == 0){
//	        	return $this->_forward('notfound');
//	        }
//	        
//	        
//	        $paypalConfig = array();
//			$paypalConfig['username'] = $account->paypal_api_username;
//            $paypalConfig['password'] = $account->paypal_api_password;
//            $paypalConfig['signature'] = $account->paypal_api_signature;
//            $paypalConfig['testMode'] = $account->paypal_api_testmode;
//			$paypalConfig['enabled'] = $account->paypal_api_enable;
//			
//    		if($deal){
//				$paypalConfig['currency'] = $deal->getCurrencyCode();
//			}
//			
//			$plugin =  new Groupon_Plugin_Gateway_PayPal($paypalConfig);
//    	}
//    	else {
    		if(!($gateway->enabled)){
    			return $form->addError(Zend_Registry::get('Zend_Translate')->_('Paypal is disabled. Please contact to administrator for more details'));
    		}
    		
    		//Get Currency of Groupon
			$paypalConfig = (array)$gateway->config;
			if($deal){
				$paypalConfig['currency'] = $deal->getCurrencyCode();
			}
        	$plugin =  new Groupon_Plugin_Gateway_PayPal((array)$paypalConfig);
    		
//    	}
        

        // Create order
        $ordersTable = Engine_Api::_()->getDbtable('orders', 'payment');
        if( !empty($this->_session->order_id) ) {
            $previousOrder = $ordersTable->find($this->_session->order_id)->current();
            if( $previousOrder && $previousOrder->state == 'pending' ) {
                $previousOrder->state = 'incomplete';
                $previousOrder->save();
            }
        }

        $ordersTable->insert(array(
                'user_id' => Engine_Api::_()->user()->getViewer()->getIdentity(),
                'gateway_id' => $gateway->gateway_id,
                'state' => 'pending',
                'creation_date' => new Zend_Db_Expr('NOW()'),
                'source_type' => 'groupon_deal',
                'source_id' => $deal->deal_id,
        ));
        $this->_session->order_id = $order_id = $ordersTable->getAdapter()->lastInsertId();
		
        // Prepare host info
        $schema = 'http://';
        if( !empty($_ENV["HTTPS"]) && 'on' == strtolower($_ENV["HTTPS"]) ) {
            $schema = 'https://';
        }
        $host = $_SERVER['HTTP_HOST'];
        
        
        $params = array();
        $params['language'] = $this->_user->language;
        $localeParts = explode('_', $this->_user->language);
        if( count($localeParts) > 1 ) {
            $params['region'] = $localeParts[1];
        }
        $params['vendor_order_id'] = md5($order_id. $groupon->title);
        $params['return_url'] = $schema . $host
                . $this->view->url(array('action' => 'returnbuy'),'groupon_general')
                . '?order_id=' . $order_id
                . '&state=' . 'return'
                .'&amount='.$form->amount->getValue();
        $params['cancel_url'] = $schema . $host
                . $this->view->url(array('action' => 'returnbuy'),'groupon_general')
                . '?order_id=' . $order_id
                . '&state=' . 'cancel';

        //Sell Now Value
        $params['price'] = floatval($deal->sale_price * intval($form->amount->getValue()));
        /*
        $priceLevelEnabled = $deal->pricelevel_enabled;
        if (!$priceLevelEnabled) {
        	$params['price'] = floatval($deal->sale_price * intval($form->amount->getValue()));
        }
        else {
        	$params['price'] = $deal->calculatePriceLevel(intval($form->amount->getValue()));
        }*/
        $params['description'] = 'sale';
        $params['amount'] = intval($form->amount->getValue());
        // Process transaction
        $grouponCore = Engine_Api::_()->groupon();
        $transaction = $grouponCore->createBuyNowTransaction($plugin, $groupon,$deal, $params);
        // Pull transaction params
        $this->view->transactionUrl = $transactionUrl = $plugin->getGateway()->getGatewayUrl();
        $this->view->transactionData = $transactionData = $transaction->getData();
        // Handle redirection
        $transactionUrl .= '?cmd=_express-checkout&token=' . $transactionData['token'];

        // Redirect to paypal
        return $this->_helper->redirector->gotoUrl($transactionUrl, array('prependBase' => false));
    }
}
